package com.sfac.springBoot.modules.common.service.impl;

import com.sfac.springBoot.config.ResourceConfigBean;
import com.sfac.springBoot.modules.common.service.ImageService;
import com.sfac.springBoot.modules.common.vo.ImageType;
import com.sfac.springBoot.modules.common.vo.Result;
import com.sfac.springBoot.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Description ImageServiceImpl
 * @Author JiangHu
 * @Date 2022/7/7 16:28
 */
@Service
public class ImageServiceImpl implements ImageService {
	private final static Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);
	@Value("${artifactId}")
	private String artifactId;
	@Autowired
	private ResourceConfigBean resourceConfigBean;

	@Override
	public Result<String> uploadImage(MultipartFile image, String type) {
		// 检查图片是否为空
		if (image.isEmpty()) {
			return new Result<>(Result.ResultStatus.ERROR.code,
					"Image is null.");
		}
		// 检查 file 是否是图片
		if (!FileUtil.isImage(image)) {
			return new Result<>(Result.ResultStatus.ERROR.code,
					"The file is not image.");
		}

		// 获取图片枚举类型
		ImageType imageType = ImageType.getImageTypeByName(type);

		// 获取目标文件绝对路径
		String destFolderPath = String.format("%s%s/%s",
				System.getProperty("os.name").toLowerCase().startsWith("win") ?
						resourceConfigBean.getWindow() :
						resourceConfigBean.getUnix(),
				artifactId,
				imageType.name);
		File destFolder = new File(destFolderPath);
		if (!destFolder.exists()) {
			destFolder.mkdirs();
		}
		String fileName = String.format("%s.%s",
				System.currentTimeMillis(),
				FileUtil.getFileType(image.getOriginalFilename()));
		String absolutePath = String.format("%s/%s", destFolderPath, fileName);

		// 获取目标文件相对路径
		String relatedPath = String.format("%s/%s/%s/%s",
				resourceConfigBean.getPrefix(),
				artifactId,
				imageType.name,
				fileName);
		LOGGER.debug("absolutePath: " + absolutePath);
		LOGGER.debug("relatedPath: " + relatedPath);

		try {
			// 移植图片文件并修改文件大小
			image.transferTo(new File(absolutePath));
			if (imageType == ImageType.PROFILE_BIG) {
				FileUtil.changeImageSize(absolutePath, absolutePath, imageType.maxWidth, imageType.maxHeight);
			}
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			return new Result<>(Result.ResultStatus.ERROR.code, "File upload error.");
		}

		return new Result<>(Result.ResultStatus.SUCCESS.code, "File upload success.", relatedPath);
	}
}
